#
# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import logging
import os
import sys
import time

from google.appengine.api import memcache
from google.appengine.api import channel
from google.appengine.api import users

import webapp2
from apiclient.errors import HttpError

import log2bq
import log2gs

import jinja2
jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

logging.getLogger().setLevel(logging.DEBUG)


class MainHandler(webapp2.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if not user:
      self.redirect(users.create_login_url(self.request.uri))
      return

    client_id = "%s" % user.user_id()
    memcache.set('client_id', client_id)

    now = time.time()
    yesterday = now - 3600 * 24

    channel_token = channel.create_channel(client_id)
    template_values = { 'channel_token': channel_token,
                        'date': time.strftime("%Y%m%d", time.localtime(yesterday)) }
    
    template = jinja_environment.get_template('index.html')
    self.response.out.write(template.render(template_values))


class StartHandler(webapp2.RequestHandler):
  def post(self):
    # TODO(proppy): add form/ui for start_time and end_time parameter
#      $.post("/start", { versions:versions, startDateTime:startDateTime, endDateTime:endDateTime, }, function() {
    #now = time.time()
    #yesterday = now - 3600 * 24
    #major, minor = os.environ["CURRENT_VERSION_ID"].split(".")
    startDateTime = int(self.request.get('startDateTime')) / (1000)
    endDateTime = int(self.request.get('endDateTime')) / (1000)
    versions = self.request.get('versions').split(",")
    logging.info(time.time())
    logging.info(versions)
    logging.info(startDateTime)
    logging.info(endDateTime)
    p = log2bq.Log2Bq(startDateTime, endDateTime, versions)
    p.start()


class QueryHandler(webapp2.RequestHandler):
  def post(self):
    query = self.request.get('query')
    jobs = log2bq.get_bigquery_service_jobs()
    try:
      result = jobs.query(projectId=bqproject,
                          body={'query':query}).execute()
      self.response.out.write(json.dumps(result))
    except HttpError, e:
      self.error(500)
      self.response.out.write(e.content)


class GetNextLogsRunStartTimeHandler(webapp2.RequestHandler):
  def get(self):
    start_time = log2bq.get_last_logs_run_end_time()
    start_date = log2gs.Log2Gs.start_date_from_time(start_time)
    self.response.headers['content-type'] = 'text/plain'
    self.response.out.write('Next logs should start be for %s (%s)' % (start_date, start_time))


app = webapp2.WSGIApplication([('/', MainHandler),
                               ('/start', StartHandler),
                               ('/query', QueryHandler),
                               ('/get_next_logs_run_start_time', GetNextLogsRunStartTimeHandler)],
                               debug=True)
